# services/transaction.py
from models.page import Page, PageType
from models.payment import BalancePayment, CashPayment, PointsPayment
from models.product import Product
from models.user import User

from services.log_service import BalanceLog, CashLog, PointsLog


class PurchaseTransaction:
    def __init__(self, user: User, page: Page, product: Product):
        self.user = user
        self.page = page
        self.product = product

    def execute(self):
        # 确保商品已设置数量
        if not hasattr(self.product, 'quantity'):
            self.product = self.product.set_amount(1)

        # 根据不同的页面选择不同的支付方式
        if self.page.type == PageType.POINTS:
            payment = PointsPayment(self.product.total_price)
        elif self.page.type == PageType.MALL:
            payment = CashPayment(self.product.total_price)
        else:
            # 默认点餐页面用余额支付
            payment = BalancePayment(self.product.total_price)

        # 生成对应的日志对象
        log_class = self._get_log_class()
        log = log_class(
            user=self.user.name,
            page=self.page,
            product=self.product,
            payment=payment
        )

        # 执行支付扣减
        self._process_payment(payment)

        return log

    def _process_payment(self, payment):
        if isinstance(payment, BalancePayment):
            self.user.deduct_balance(payment.amount)
        elif isinstance(payment, PointsPayment):
            self.user.add_points(-payment.amount)
        # 现金支付的话，对用户余额或积分没有直接影响，这里就不做任何操作

    def _get_log_class(self):
        return {
            PageType.ORDER: BalanceLog,
            PageType.MALL: CashLog,
            PageType.POINTS: PointsLog
        }[self.page.type]
